<?php
/*	Discuz第三方框架 阿里云API网关扩展
 *
 *
 */
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class CURL {
	var $Url ='';
	var $Https = 0;
	var $Curl;
	var $File;
	
	function send($Method='GET',$url,$Data,$headers){
		$this->Https = 0;
		$parse_url = parse_url($url);
		if(strtolower($parse_url['scheme']) =='https'){
			$this->Https = 1;
		}
		unset($parse_url);
		
		if($Method =='POST' && $Data) {
			if(!is_array($Data)) {
				parse_str($Data, $Data);
			}
			$this->postFormat($Data, $Datanew);
			$Data = $Datanew;
			unset($Datanew);
			
		}elseif($Method =='PUT' && $Data) {
			$this->File = fopen($Data, 'r');
		}
		
		$url = trim($url);
		$ch = curl_init();  
		
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		
		curl_setopt($ch, CURLOPT_HEADER, true); //输出header内容到页面
		
		curl_setopt($ch, CURLOPT_USERAGENT, 'Slimbbs/1.0.1'); //定义USERAGENT Slimbbs
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, false); //连接选择  使用缓存中的连接
		curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //查找次数 最多查找2次
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //在发起连接前等待的时间 5秒w未连接上则直接退出
		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书  
		if($this->Https){
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); //检查证书中是否设置域名
		}else{
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}
		
		curl_setopt($ch, CURLOPT_TIMEOUT, 30); //发起连接后持续时间  30秒后直接断开
		curl_setopt($ch, CURLOPT_NOSIGNAL, true); //防止毫秒级时间出现bug
		
		if($headers){
			if(is_array($headers)){
				foreach($headers as $key => $value){
					$headers[$key] = $key.':'.$value;
				}
			}
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		}
		
		switch ($Method){
			case 'PUT' :
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
				if($this->File){
					curl_setopt ($ch, CURLOPT_INFILESIZE, filesize($this->File));
					curl_setopt ($ch, CURLOPT_INFILE, $this->File);
					curl_setopt ($ch, CURLOPT_UPLOAD, true);
				}
				break;
			case 'DELETE':
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
				break; 
			case 'HEAD':
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
				curl_setopt($ch, CURLOPT_NOBODY, 1);
				break;
			case 'POST':
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $Data);
				break;
		}
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch); 
		
		if(!$errno && $status['http_code'] == '200') {
			$data = substr($data, $status['header_size']);
			$data = !$limit ? $data : substr($data, 0, $limit);
		}
		
		$return = array('status'=>$status,'httpcode'=>$status['http_code'],'data'=>$data,'errno'=>$errno);
		unset($data,$status,$errno);
		return $return;  
	}
	
	function postFormat($post, &$result, $key = '') {
		foreach($post as $k => $v) {
			$_k = $key ? $key.'['.$k.']' : $k;
			if(is_array($v)) {
				$this->postFormat($v, $result, $_k);
			} else {
				$result[$_k] = $v;
			}
		}
	}
}

?>